"use client"

import Link from "next/link"
import Image from "next/image"
import { useState } from "react"
import { useRouter } from 'next/navigation' // Import useRouter
import { RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { authRegister} from "@/lib/request"
import {post} from '@/lib/api'
import { toast } from "@/hooks/use-toast"
import { Toaster } from "@/components/ui/toaster"
export default function Register() {
  const router = useRouter() // Initialize useRouter
  const [captchaLoading, setCaptchaLoading] = useState(false)
  const [smsLoading, setSmsLoading] = useState(false)
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    // phone: '',
    // smsCode: '',
    // captcha: ''
  })
  const [error, setError] = useState('')

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target
    setFormData(prev => ({
      ...prev,
      [id]: value
    }))
  }

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')

    // 表单验证
    if (!formData.username || !formData.email || !formData.password || !formData.confirmPassword) {
      setError('请填写所有必填字段')
      return
    }

    if (formData.password !== formData.confirmPassword) {
      setError('两次输入的密码不一致')
      return
    }

    try {
      const response = await post('/auth/register', formData)
      // 处理注册成功后的逻辑
      //注册成功，跳转到登录页面
      if(response.code === 201){
         router.push('/login')
      } else {
        //用component 提示错误
        console.log('走到这里了')
        toast({
          description: response.message || '未知错误',
          variant: 'destructive'
        })
      }
    } catch (err) {
      console.error('注册请求失败:', err)
      toast({
        description: '请求失败，请稍后重试。',
        variant: 'destructive'
      })
    }
  }

  const refreshCaptcha = () => {
    setCaptchaLoading(true)
    // Simulate loading
    setTimeout(() => setCaptchaLoading(false), 500)
  }

  const sendSmsCode = () => {
    setSmsLoading(true)
    // Simulate loading
    setTimeout(() => setSmsLoading(false), 1000)
  }

  return (
    <div className="flex min-h-screen flex-col bg-gray-100">
      {/* Header */}
      <header className="sticky top-0 z-10 flex h-14 items-center justify-between border-b bg-white px-4 shadow-sm">
        <div className="flex items-center gap-8">
          <Link href="#" className="text-2xl font-bold text-gray-800">
            过早客
          </Link>
          <nav className="hidden md:flex">
            <ul className="flex items-center gap-6">
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  首页
                </Link>
              </li>
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  节点
                </Link>
              </li>
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  成员
                </Link>
              </li>
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  广告招放
                </Link>
              </li>
            </ul>
          </nav>
        </div>
        <div className="flex items-center gap-4">
          <div className="relative w-64">
            <Input
              type="search"
              placeholder="Search"
              className="h-9 w-full rounded-md border border-gray-300 pl-3 pr-10 text-sm"
            />
          </div>
          <div className="flex items-center gap-2">
            <Link href="/login" className="text-sm text-gray-600 hover:text-gray-900">
              登录
            </Link>
            <Link href="/register" className="text-sm text-gray-600 hover:text-gray-900">
              注册
            </Link>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="container mx-auto flex flex-col gap-4 px-4 py-6 md:flex-row">
        {/* Left Content - Registration Form */}
        <div className="w-full rounded-md bg-white p-6 md:w-3/4">
          <h1 className="mb-6 text-xl font-medium">欢迎加入</h1>

          <form className="max-w-md" onSubmit={handleRegister}>
            {error && (
              <div className="mb-4 text-red-500 text-sm">
                {error}
              </div>
            )}
            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="username" className="mb-1 block w-24 text-right text-sm font-medium">
                  用户名
                </label>
                <div className="flex-1 pl-4">
                  <Input 
                    id="username" 
                    className="w-full" 
                    value={formData.username}
                    onChange={handleInputChange}
                    required
                  />
                  <p className="mt-1 text-xs text-gray-500">用户名由字母开头，只能含有字母、数字或者下划线</p>
                </div>
              </div>
            </div>

            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="email" className="mb-1 block w-24 text-right text-sm font-medium">
                  E-mail
                </label>
                <div className="flex-1 pl-4">
                  <Input 
                    id="email" 
                    type="email" 
                    className="w-full" 
                    value={formData.email}
                    onChange={handleInputChange}
                    required
                  />
                  <p className="mt-1 text-xs text-gray-500">请输入你的E-mail，便于登录和找回密码</p>
                </div>
              </div>
            </div>

            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="password" className="mb-1 block w-24 text-right text-sm font-medium">
                  密码
                </label>
                <div className="flex-1 pl-4">
                  <Input 
                    id="password" 
                    type="password" 
                    className="w-full" 
                    value={formData.password}
                    onChange={handleInputChange}
                    required
                  />
                  <p className="mt-1 text-xs text-gray-500">密码不少于6个字符</p>
                </div>
              </div>
            </div>

            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="confirmPassword" className="mb-1 block w-24 text-right text-sm font-medium">
                  密码 (确认)
                </label>
                <div className="flex-1 pl-4">
                  <Input 
                    id="confirmPassword" 
                    type="password" 
                    className="w-full" 
                    value={formData.confirmPassword}
                    onChange={handleInputChange}
                    required
                  />
                  <p className="mt-1 text-xs text-gray-500">请再次输入密码</p>
                </div>
              </div>
            </div>

            {/* <div className="mb-4"> 
              <div className="flex items-center justify-between">
                <label htmlFor="captcha" className="mb-1 block w-24 text-right text-sm font-medium">
                  验证码
                </label>
                <div className="flex-1 pl-4">
                  <div className="flex items-center gap-2">
                    <div className="relative h-16 w-48 overflow-hidden rounded border">
                      <Image
                        src="/placeholder.svg?height=64&width=192"
                        alt="CAPTCHA"
                        width={192}
                        height={64}
                        className="h-full w-full object-cover"
                      />
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={refreshCaptcha}
                      disabled={captchaLoading}
                      className="h-10 whitespace-nowrap"
                    >
                      {captchaLoading ? (
                        <RefreshCw className="mr-1 h-4 w-4 animate-spin" />
                      ) : (
                        <RefreshCw className="mr-1 h-4 w-4" />
                      )}
                      换一张
                    </Button>
                  </div>
                  <p className="mt-1 text-xs text-gray-500">请拖动左侧侧滑块还原图片</p>
                </div>
              </div>
            </div>

            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="phone" className="mb-1 block w-24 text-right text-sm font-medium">
                  手机号
                </label>
                <div className="flex-1 pl-4">
                  <Input id="phone" className="w-full" />
                  <p className="mt-1 text-xs text-gray-500">请输入手机号</p>
                </div>
              </div>
            </div>

            <div className="mb-6">
              <div className="flex items-center justify-between">
                <label htmlFor="sms-code" className="mb-1 block w-24 text-right text-sm font-medium">
                  短信验证
                </label>
                <div className="flex-1 pl-4">
                  <div className="flex gap-2">
                    <Input id="sms-code" className="flex-1" />
                    <Button onClick={sendSmsCode} disabled={smsLoading} className="bg-blue-500 hover:bg-blue-600">
                      {smsLoading ? "发送中..." : "获取验证码"}
                    </Button>
                  </div>
                  <p className="mt-1 text-xs text-gray-500">请输入验证码</p>
                </div>
              </div>
            </div> */}

            <div className="flex justify-center md:justify-start md:pl-28">
              <Button type="submit" className="bg-green-500 hover:bg-green-600 px-8">注册</Button>
            </div>
          </form>
        </div>

        {/* Right Sidebar - About */}
        <div className="w-full md:w-1/4">
          <div className="rounded-md bg-white p-4">
            <h3 className="mb-3 font-medium">关于</h3>
            <div className="text-sm text-gray-600 space-y-2">
              <p>
                Guozaoke.com起源于武汉，这里汇聚了一群追求美好，热爱生活的人。他们相信，无论是对论坛兴趣的话题，还是自由的表达观点，一个高效，友好，不断进化的信息交流平台将会成为我们学习，工作，生活的一部分。
              </p>
              <p>从中所能获得有价值的资讯，丰富个人阅历，也能帮助更多寻找答案的人解决问题。</p>
            </div>
          </div>
        </div>
      </main>
      <Toaster />
    </div>
  )
}
